package com.itheima.reggie.filter;



import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.GlobalThread;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.security.servlet.AntPathRequestMatcherProvider;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author mff
 * @date 2022/6/8 10:22
 * @mood happy
 */
@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //    创建比较器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        转换servlet
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        定义需要放行的地址
        String[] urls = new  String[]{
//          java ant url 风格
          "/backend/**",
          "/front/**",
          "/employee/login",
          "/employee/logout",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };
//        判断是否需要拦截
        boolean check = check(urls, request.getRequestURI());
//        放行
        log.info("用户登录、退出操作，不拦截，直接放行");
        if (check){
            filterChain.doFilter(request,response);
            return;
        }

//       不放行就要验证，1、查看是否已经登陆过
/*        Long existId = (Long) request.getSession().getAttribute("employee");
        if (existId!=null){
            log.info("用户登录过了，直接放行");
            Long id = (Long) request.getSession().getAttribute("employee");
            GlobalThread.setThread(id);
            filterChain.doFilter(request,response);
            log.info("删除内存资源");
            GlobalThread.remove();
            return;
        }*/

//        被拦截，首先从session中判断登录状态
        if(request.getSession().getAttribute("employee")!=null){
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            BaseContext.removeCurrentId();
            return;
        }

        User user = (User) request.getSession().getAttribute("user");
        User newUser = (User) request.getSession().getAttribute("newUser");
        if(user!=null){
            BaseContext.setCurrentId(user.getId());
            filterChain.doFilter(request,response);
            BaseContext.removeCurrentId();
            return;
        }
        if(newUser!=null){
            BaseContext.setCurrentId(newUser.getId());
            filterChain.doFilter(request,response);
            BaseContext.removeCurrentId();
            return;
        }

//        未登录，向前端返回错误信息
        log.info("没登陆还想访问？");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    private boolean check(String[] urls, String url) {
        for (String s : urls) {
            if (PATH_MATCHER.match(s,url)) {
                return true;
            }
        }
        return false;
    }
}
